package cn.zhoutao.basic.interceptor;

import cn.zhoutao.auth.domain.Permission;
import cn.zhoutao.auth.mapper.PermissionMapper;
import cn.zhoutao.basic.anno.PreAuthorize;
import cn.zhoutao.basic.jwt.JwtUtils;
import cn.zhoutao.basic.jwt.LoginResult;
import cn.zhoutao.basic.jwt.Payload;
import cn.zhoutao.basic.jwt.RsaUtils;
import cn.zhoutao.user.domain.Logininfo;
import cn.zhoutao.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author:MrZhou
 * @Date:2022/6/18 21:33
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;


    @Value("${rsa.pub}")
    public String publicKeyValue;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //从请求头中获取u-token
        String token = request.getHeader("U-TOKEN");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        //拿到了
        if (!StringUtils.isEmpty(token)){
           /* //根据u-token从redis中获取登录信息
            Object loginTmp = redisTemplate.opsForValue().get(token);*/

            //解密jwt串，得到登录人和登陆人的权限
            //获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            //使用公钥去解密(payload:载荷)
            Payload<LoginResult> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginResult.class);
            LoginResult loginResult = payload.getUserInfo();


            if (loginResult!=null){
                //增加权限校验，===即登录过后需要校验是否有权限访问一些资源
                //区分是否是员工，时就需要校验
                Logininfo logininfo = loginResult.getLogininfo();
                if(logininfo.getType()==0){//代表使员工就要校验权限
                    //得到当前请求的资源url
                    HandlerMethod method = (HandlerMethod) handler;
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    if (annotation!=null){
                        String currentSn = annotation.value();//本次请求的sn
                        //查询出当前登录人拥有的权限资源：permiss
                       // List<String> permissions = permissionMapper.loadPermissionsByLogininfoId(logininfo.getId());
                        //判断permission是否包含url
                        if (!loginResult.getPermissions().contains(currentSn)){
                            //不包含就提示：权限不足，请联系管理员处理
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;//阻止放行
                        }
                    }
                        //包含的话就放行，说明有权限访问

                }
                //刷新过期时间
                //redisTemplate.opsForValue().set(token, loginTmp, 30, TimeUnit.MINUTES);
                return true;//登录了就 放行
            }
        }
            //拿不到就去登陆
            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"message\":\"noLogin\"}");
            writer.flush();
            writer.close();
            return false;//阻止放行
        }

}
